package com.example.groudChat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class Client {


    private final String host;
    private final  int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run(){


        EventLoopGroup clientGroup= new NioEventLoopGroup();
        try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(clientGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("decoder",new StringEncoder());
                        pipeline.addLast("encoder",new StringDecoder());
                        pipeline.addLast(new ClientHandler());

                    }
                });

            ChannelFuture sync = bootstrap.connect(host, port).sync();
            Channel channel = sync.channel();
            System.out.println(channel.localAddress()+"+++++++++++++++");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext())
            {
                String s = scanner.nextLine();
                channel.writeAndFlush(s+"\r\n");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
   clientGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new Client("127.0.0.1",7000).run();
    }
}
